import useUserStore from "@/store/modules/user";
import axios from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: '/api',
    timeout: 15000
});

// 请求拦截器
request.interceptors.request.use(config => {
    let userStore = useUserStore()
    if(userStore.userInfo.token){
        config.headers.token = userStore.userInfo.token
    }
    return config
})

// 响应拦截器
request.interceptors.response.use((response) => {
    const code = response.data.code
    if (code === 200) {
        return response.data
    } else {
        ElMessage({
            type: 'error',
            message: response.data.message
        })
        return Promise.reject(new Error(response.data.message))
    }
}, (error) => {
    return Promise.reject(new Error(error.message))
})

export default request;